package com.example.myapplication;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
public class MyRecyclerAdapter  extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
    private List<Fruit> fruitList;
    private int resourceId;

    public MyRecyclerAdapter(List<Fruit> fruitList, int resourceId) {
        this.fruitList = fruitList;
        this.resourceId = resourceId;
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(resourceId,parent,false);
        ViewHolder holder = new ViewHolder(itemView);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
       Fruit fruit = fruitList.get(position);
       holder.fruitImage.setImageResource(fruit.getImageId());
       holder.fruitName.setText(fruit.getName());

    }

    @Override
    public int getItemCount() {
        return fruitList.size();
    }

    static  class ViewHolder extends RecyclerView.ViewHolder{
        //定义Item中对应的两个组件
        ImageView fruitImage;
        TextView  fruitName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            //获取到Item中对应的组件
            fruitImage = itemView.findViewById(R.id.fruit_image);
            fruitName = itemView.findViewById(R.id.fruit_name);
        }
    }
}
